<template>
  <div class="header">
    我的头像
  </div>
  <div class="content">
    <div class="box">
      <div class="left">
        <!-- 上传容器 -->
        <div class="upload-container">
          <!-- 上传组件 -->
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :show-file-list="false"
              :limit="1"
              :on-change="handleChange"
              :class="{ 'hidden-upload': imageUrl }"
          >
            <template v-if="!imageUrl">
              <el-icon><Plus /></el-icon>
            </template>
          </el-upload>

          <!-- 图片预览区域 -->
          <div v-if="imageUrl" class="preview-area">
            <img :src="imageUrl" class="preview-image" />
            <div class="mask-layer">
              <el-icon @click="handlePreview"><ZoomIn /></el-icon>
              <el-icon @click="handleReplace"><Upload /></el-icon>
              <el-icon @click="handleRemove"><Delete /></el-icon>
            </div>
          </div>

          <!-- 上传按钮 -->
          <div class="upload-btn">
            <el-button
                type="primary"
                @click="handleUpload"
                :loading="uploading"
                v-if="imageUrl"
            >
              {{ uploading ? '上传中...' : '确认上传' }}
            </el-button>
          </div>

          <!-- 预览对话框 -->
          <el-dialog v-model="dialogVisible" title="图片预览">
            <img :src="imageUrl" class="full-preview" />
          </el-dialog>
        </div>
      </div>
      <el-divider direction="vertical" style="height: 200px"></el-divider>
      <div class="right">
        <div class="pic">
          <img :src="currentAvatar" width="120" alt="">
        </div>
        当前头像
      </div>
    </div>
  </div>
</template>
<script setup>
import {onMounted, onUnmounted, ref} from 'vue'
import axios from 'axios'
import {ElMessage} from "element-plus";
import http from "@/api/http.js";
import emitter from "@/utils/emitter.js";
import {useUserStore} from "@/stores/userInfoStore.js";
import {updateAvatar} from "@/api/api.js";
import {uploadAvatarUrl} from "@/constant/url.js";

const imageUrl = ref('')     // 当前显示的图片URL
const rawFile = ref(null)    // 原始文件对象
const dialogVisible = ref(false)
const uploading = ref(false)

// 文件选择处理
const handleChange = (file) => {
  // 生成预览URL
  if (file.raw) {
    // 释放旧URL内存
    if (imageUrl.value) URL.revokeObjectURL(imageUrl.value)

    imageUrl.value = URL.createObjectURL(file.raw)
    rawFile.value = file.raw
  }
}

// 预览大图
const handlePreview = () => {
  dialogVisible.value = true
}

// 替换图片
const handleReplace = () => {
  // 通过隐藏的input触发文件选择
  document.querySelector('.el-upload input[type="file"]').click()
}

// 删除图片
const handleRemove = () => {
  URL.revokeObjectURL(imageUrl.value)
  imageUrl.value = ''
  rawFile.value = null
}
// const uploadUrl = ref("http://localhost:8080/user/common/upload/image")
// 执行上传
const handleUpload = async () => {
  if (!rawFile.value) return

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', rawFile.value)

    const res = await http.post(uploadAvatarUrl, formData)


    // 替换为服务器返回的真实URL（示例）
    imageUrl.value = res.data
    console.log(res.data)

    const res1 = await updateAvatar(imageUrl.value)
    console.log(res1)
    if(res1.code == 200){
      ElMessage.success("更新头像成功")
      currentAvatar.value = imageUrl.value
      emitter.emit("switchAvatar",imageUrl.value)
      useUserStore().setUserAvatar(imageUrl.value)
    }
    ElMessage.success('上传成功')
  } catch (err) {
    ElMessage.error(`上传失败: ${err.message}`)
  } finally {
    uploading.value = false
  }
}

// 内存清理
onUnmounted(() => {
  if (imageUrl.value) URL.revokeObjectURL(imageUrl.value)
})


const currentAvatar = ref("/img/avatar.webp")
onMounted(()=>{
  emitter.on("userInfo",(info)=>{
    console.log("收到用户信息")
    console.log(info)
    currentAvatar.value = info.userAvatar;
  })
  currentAvatar.value= useUserStore().userInfo.userAvatar
})
</script>
<style lang="scss" scoped>
.header{
  height: 56px;
  border: 1px solid #ccc;
  box-sizing: border-box;
  padding-left: 50px;
  padding-top: 16px;
  color: #2ae6ff;
}


.upload-btn{
  position: relative;
  top: 200px;
  left: 50px;
}
.upload-container {
  position: relative;
  width: 178px;
  height: 178px;
}

/* 隐藏默认上传组件 */
:deep(.hidden-upload .el-upload) {
  display: none;
}

.preview-area {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 0 4px rgba(0,0,0,.1);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.mask-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  opacity: 0;
  transition: opacity .3s;
}

.mask-layer:hover {
  opacity: 1;
}

.mask-layer .el-icon {
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 8px;
  background: rgba(255,255,255,.2);
  border-radius: 50%;
}

.full-preview {
  width: 100%;
  max-height: 70vh;
  object-fit: contain;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.content{
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  .box{
    display: flex;
    justify-content: center;
    align-items: center;
    .left{
      display: flex;
      justify-content: center;
      align-items: center;
      width: 300px;
      height: 200px;

    }
    .right{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 200px;
      height: 200px;
      .pic{
        width: 120px;
        height: 120px;
        overflow: hidden;
        border-radius: 50%;
        margin-bottom: 20px;
      }
    }
  }
}
</style>